export default class DeviceToolTopology {

  #signals
  #displayer

  constructor(displayer) {
    this.#signals = displayer.signals
    this.#displayer = displayer
  }

  traverseTopology(devices) {
    let scope = this
    if (devices === null) return
    devices.forEach((device) => {
      // 当前设备
      let obj = scope.#displayer.objectByUuid(device.id)
      let deviceChild = device.children
      for (let i in deviceChild) {
        let objChild = scope.#displayer.objectByUuid(deviceChild[i].id)
        scope.#displayer.signals.deviceLine.dispatch(obj, objChild)
      }
      this.traverseTopology(device.children)
    })

  }

  deviceTopology(object) {
    const scope = this
    if (object !== null) {
      // 根据设备id获取设备父子关系
      this.#displayer.request.getAction('/display/getDeviceTopology', {instanceId: object.uuid}).then((data) => {
        if (data.success) {
          let devices = data.result
          scope.#displayer.signals.deviceDeline.dispatch()
          this.traverseTopology(devices)
        }
      })
      this.createCloseBtn()
    }
  }

  deviceTopologyAll() {
    const scope = this
    scope.#displayer.request.getAction('/display/getAllDeviceTopology').then((data) => {
      if (data.success) {
        let devices = data.result
        scope.#displayer.signals.deviceDeline.dispatch()
        this.traverseTopology(devices)
      }
    })
    this.createCloseBtn()
  }

  deviceDetopology() {
    this.#displayer.signals.deviceDeline.dispatch()
  }

  createCloseBtn() {
    let scope = this
    if (!document.getElementById('topology-btn')) {
      let closeTopologyBtn = document.createElement('a')
      closeTopologyBtn.href = 'javascript:;'
      closeTopologyBtn.text = '关闭拓扑'
      closeTopologyBtn.id = 'topology-btn'
      // container.setStyle('display', ['none'])
      closeTopologyBtn.addEventListener("click", e => {
        e.stopPropagation()
        scope.deviceDetopology()
        closeTopologyBtn.style.display = 'none'
      })

      let viewport = document.getElementById('viewport')
      viewport.insertBefore(closeTopologyBtn, document.getElementById('toolbar'))
    } else {
      document.getElementById('topology-btn').style.display = 'block'
    }
  }
}